<template>
    <div class="material-ledger-container">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="二维码(包含)">
                <el-input v-model="formInline.qecode" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getTableData()" style="background-color: teal;"><el-icon>
                        <Search />
                    </el-icon></el-button>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div class="operation-bar">
            <el-button size="small" style="background-color: orangered;color: white;"
                @click="deleteanageOperational()" :disabled="!selectedRows.length" :loading="loading">批量删除</el-button>
            <el-button size="small" style="background-color: teal;color: white;" @click="addOperational" :loading="loading">添加</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table
            v-loading="loading"
            :data="tableData"
            border
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column prop="materialCode" label="物料编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="materialDescription" label="物料描述" min-width="180" show-overflow-tooltip />
            <el-table-column prop="qrCode" label="二维码" min-width="200" show-overflow-tooltip />
            <el-table-column prop="batch" label="批次" min-width="100" show-overflow-tooltip />
            <el-table-column prop="processLine" label="工艺路线" min-width="120">
                <template #default="{ row }">
                    <el-tag :type="getProcessLineType(row.processLine)">
                        {{ getProcessLineName(row.processLine) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="specificationType" label="型号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="materialType" label="物料类型" min-width="100">
                <template #default="{ row }">
                    <el-tag :type="getMaterialTypeTag(row.materialType)">
                        {{ getMaterialTypeName(row.materialType) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="state" label="状态" min-width="100">
                <template #default="{ row }">
                    <el-tag :type="getStateType(row.state)">
                        {{ getStateName(row.state) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
                <template #default="{ row }">
                    <el-button 
                        type="primary" 
                        link
                        @click="updateOperational(row)"
                    >
                        编辑
                    </el-button>
                    <el-button 
                        type="danger" 
                        link
                        @click="deleteOperational(row.id)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增弹窗 -->
        <el-dialog
            v-model="dialogTableVisible1"
            title="添加"
            width="1000"
            draggable
        >
            <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
            >
                <div width="1000" height="1500">
                    <el-form-item label="二维码/条形码" prop="qrCode">
                        <el-input v-model="ruleForm.qrCode" disabled />
                    </el-form-item>
                    <el-form-item label="物料编码" prop="materialCode">
                        <el-input v-model="ruleForm.materialCode" disabled />
                    </el-form-item>
                    <el-form-item label="物料描述" prop="materialDescription">
                        <el-input v-model="ruleForm.materialDescription" />
                    </el-form-item>
                    <el-form-item label="批次" prop="batch">
                        <el-input v-model="ruleForm.batch" disabled/>
                    </el-form-item>
                    <el-form-item label="规格型号" prop="specificationType">
                        <el-input v-model="ruleForm.specificationType" />
                    </el-form-item>
                    <el-form-item label="物料类型" prop="materialType">
                        <el-select v-model="ruleForm.materialType">
                            <el-option label="请选择" :value="0" />
                            <el-option label="成品" :value="1" />
                            <el-option label="半成品" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="工艺线路" prop="processLine">
                        <el-select v-model="ruleForm.processLine">
                            <el-option label="请选择" :value="0" />
                            <el-option label="磁阻传感器" :value="1" />
                            <el-option label="压力传感器" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" prop="name">
                        <el-radio-group v-model="ruleForm.state">
                            <el-radio :value="1">正常</el-radio>
                            <el-radio :value="2">已删除</el-radio>
                            <el-radio :value="3">已禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
            </el-form>
            <div style="margin-left: 850px;width: 800px;margin-top: 20px;">
                <el-form-item>
                    <el-button type="primary" @click="submitForm1(ruleFormRef)">
                        确定
                    </el-button>
                    <el-button @click="dialogTableVisible1 = false">取消</el-button>
                </el-form-item>
            </div>
        </el-dialog>

        <!-- 更新弹窗 -->
        <el-dialog
            v-model="dialogTableVisible2"
            title="编辑"
            width="1000"
            draggable
        >
            <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
            >
                <div width="1000" height="1500">
                    <el-form-item label="二维码/条形码" prop="qrCode">
                        <el-input v-model="ruleForm.qrCode" disabled />
                    </el-form-item>
                    <el-form-item label="物料编码" prop="materialCode">
                        <el-input v-model="ruleForm.materialCode" disabled />
                    </el-form-item>
                    <el-form-item label="物料描述" prop="materialDescription">
                        <el-input v-model="ruleForm.materialDescription" />
                    </el-form-item>
                    <el-form-item label="批次" prop="batch">
                        <el-input v-model="ruleForm.batch" disabled/>
                    </el-form-item>
                    <el-form-item label="规格型号" prop="specificationType">
                        <el-input v-model="ruleForm.specificationType" />
                    </el-form-item>
                    <el-form-item label="物料类型" prop="materialType">
                        <el-select v-model="ruleForm.materialType">
                            <el-option label="请选择" :value="0" />
                            <el-option label="成品" :value="1" />
                            <el-option label="半成品" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="工艺线路" prop="processLine">
                        <el-select v-model="ruleForm.processLine">
                            <el-option label="请选择" :value="0" />
                            <el-option label="磁阻传感器" :value="1" />
                            <el-option label="压力传感器" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" prop="name">
                        <el-radio-group v-model="ruleForm.state">
                            <el-radio :value="1">正常</el-radio>
                            <el-radio :value="2">已删除</el-radio>
                            <el-radio :value="3">已禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
            </el-form>
            <div style="margin-left: 850px;width: 800px;margin-top: 20px;">
                <el-form-item>
                    <el-button type="primary" @click="submitForm2(ruleFormRef)">
                        确定
                    </el-button>
                    <el-button @click="dialogTableVisible2 = false">取消</el-button>
                </el-form-item>
            </div>
        </el-dialog>

        <!-- 导入弹窗 -->
        <el-dialog
            v-model="importDialogVisible"
            title="批量导入"
            width="500px"
        >
            <el-upload
                class="upload-demo"
                drag
                action="/api/MaterialManagement/ImportMaterialLedger"
                :headers="uploadHeaders"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                accept=".xlsx,.xls"
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        只能上传 xlsx/xls 文件
                    </div>
                </template>
            </el-upload>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import http from '@/api/http'
import { UploadFilled } from '@element-plus/icons-vue'

// 状态定义
const loading = ref(false)
const submitLoading = ref(false)
const dialogTableVisible1 = ref(false)
const dialogTableVisible2 = ref(false)
const importDialogVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const ruleFormRef = ref<FormInstance>()
const selectedRows = ref<any[]>([])

// 搜索表单
const formInline = reactive({
    qecode: ''
})

// 表单数据
const ruleForm = reactive({
    id: 0,
    qrCode: '',
    materialCode: '',
    materialDescription: '',
    batch: '',
    specificationType: '',
    materialType: '',
    processLine: '',
    state: 1
})

// 表格数据
const tableData = ref([])

// 选项定义
const processLineOptions = [
    { value: 1, label: '磁阻传感器' },
    { value: 2, label: '压力传感器' }
]

const materialTypeOptions = [
    { value: 1, label: '成品' },
    { value: 2, label: '半成品' }
]

const stateOptions = [
    { value: 1, label: '正常' },
    { value: 2, label: '已删除' },
    { value: 3, label: '已禁用' }
]

// 表单校验规则
const rules = reactive<FormRules>({
    qrCode: [
        { required: true, message: '二维码/条形码不能为空', trigger: 'blur' },
    ],
    materialCode: [
        {
            required: true,
            message: '物料编码不能为空',
            trigger: 'blur',
        },
    ],
    materialDescription: [
        {
            required: true,
            message: '物料描述不能为空',
            trigger: 'blur',
        },
    ],
    batch: [
        {
            required: true,
            message: '批次不能为空',
            trigger: 'blur',
        },
    ],
    specificationType: [
        {
            required: true,
            message: '规格型号不能为空',
            trigger: 'blur',
        },
    ],
    materialType: [
        {
            required: true,
            message: '物料类型不能为空',
            trigger: 'blur',
        },
    ],
    processLine: [
        {
            required: true,
            message: '工艺路线不能为空',
            trigger: 'blur',
        },
    ],
    state: [
        {
            required: true,
            message: '状态不能为空',
            trigger: 'blur',
        },
    ],
    desc: [
        { required: true, message: 'Please input activity form', trigger: 'blur' },
    ],
})

// 上传配置
const uploadHeaders = {
    // 如果需要认证token等，在这里添加
}

// 生命周期钩子
onMounted(() => {
    getTableData()
})

// 方法定义
const getTableData = () => {
    loading.value = true
    http.get('/api/MaterialManagement/GetMaterialLedger?qecode=' + formInline.qecode)
        .then(res => {
            tableData.value = res.data
        })
        .catch(() => {
            ElMessage.error('获取数据失败')
        })
        .finally(() => {
            loading.value = false
        })
}

const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows
}

const addOperational = async () => {
    ruleForm.id = 0
    ruleForm.materialDescription = ''
    ruleForm.specificationType = ''
    ruleForm.materialType = ''
    ruleForm.processLine = ''
    ruleForm.state = 1
    await getAutoFields()
    dialogTableVisible1.value = true
}

const updateOperational = (row: any) => {
    ruleForm.id = row.id
    ruleForm.qrCode = row.qrCode
    ruleForm.materialCode = row.materialCode
    ruleForm.materialDescription = row.materialDescription
    ruleForm.batch = row.batch
    ruleForm.specificationType = row.specificationType
    ruleForm.materialType = row.materialType
    ruleForm.state = row.state
    ruleForm.processLine = row.processLine
    dialogTableVisible2.value = true
}

const deleteOperational = (id: number) => {
    ElMessageBox.confirm(
        '你确定要删除吗?',
        '删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            http.post('/api/MaterialManagement/DeleteMaterialLedger?id=' + id).then(res => {
                ElMessage.success('删除成功')
                getTableData()
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除被取消',
            })
        })
}

const deleteanageOperational = () => {
    ElMessageBox.confirm(
        '你确定要删除这几个数据吗',
        '删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            http.post('/api/MaterialManagement/DeleteAnageMaterialLedger?Id=' + selectedRows.value.map(row => row.id).join(',')).then(res => {
                ElMessage.success('删除成功')
                getTableData()
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除被取消',
            })
        })
}

const getAutoFields = async () => {
    try {
        loading.value = true
        const [qrCodeRes, materialCodeRes, batchRes] = await Promise.all([
            http.get('/api/TeamManagement/GetCode'),
            http.get('/api/Bom/GetBomCode'),
            http.get('/api/Bom/GetBomCode') // 假设批次和物料编码接口相同
        ])
        ruleForm.qrCode = qrCodeRes.toString()
        ruleForm.materialCode = materialCodeRes.toString()
        ruleForm.batch = batchRes.toString()
    } catch (error) {
        ElMessage.error('自动生成字段失败')
    } finally {
        loading.value = false
    }
}

const submitForm1 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!', ruleForm)
            http.post('/api/MaterialManagement/AddMaterialLedger', ruleForm).then(res => {
                ElMessage.success('新增成功')
                dialogTableVisible1.value = false
                getTableData()
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const submitForm2 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!', ruleForm)
            http.post('/api/MaterialManagement/UpdateMaterialLedger', ruleForm).then(res => {
                ElMessage.success('更新成功')
                dialogTableVisible2.value = false
                getTableData()
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const handleImport = () => {
    importDialogVisible.value = true
}

const handleExport = async () => {
    try {
        const res = await http.get('/api/MaterialManagement/ExportMaterialLedger', {
            responseType: 'blob'
        })
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = `物料台账_${new Date().getTime()}.xlsx`
        link.click()
    } catch (error) {
        ElMessage.error('导出失败')
    }
}

const handleUploadSuccess = () => {
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    getTableData()
}

const handleUploadError = () => {
    ElMessage.error('导入失败')
}

// 工具方法
const getProcessLineType = (type: number) => {
    return type === 1 ? 'primary' : 'success'
}

const getProcessLineName = (type: number) => {
    return processLineOptions.find(item => item.value === type)?.label || '-'
}

const getMaterialTypeTag = (type: number) => {
    return type === 1 ? 'success' : 'warning'
}

const getMaterialTypeName = (type: number) => {
    return materialTypeOptions.find(item => item.value === type)?.label || '-'
}

const getStateType = (state: number) => {
    switch (state) {
        case 1: return 'success'
        case 2: return 'danger'
        case 3: return 'info'
        default: return ''
    }
}

const getStateName = (state: number) => {
    return stateOptions.find(item => item.value === state)?.label || '-'
}
</script>

<style lang="scss" scoped>
.material-ledger-container {
    padding: 32px 24px;
    background: #f7f8fa;
    min-height: 100vh;

    .demo-form-inline {
        background: #fff;
        padding: 20px 24px 8px 24px;
        border-radius: 8px;
        margin-bottom: 18px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.03);
        display: flex;
        flex-wrap: wrap;
        gap: 16px 24px;
    }

    .operation-bar {
        margin-bottom: 16px;
        display: flex;
        gap: 12px;
        align-items: center;
        background: #fff;
        padding: 12px 20px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.03);
    }

    .el-table {
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0,0,0,0.03);
    }

    .el-table th, .el-table td {
        font-size: 15px;
    }

    .el-table--striped .el-table__body tr.el-table__row--striped td {
        background: #f5f7fa;
    }

    .el-table__body tr:hover > td {
        background: #e6f7ff !important;
    }

    .el-dialog {
        border-radius: 10px;
    }
    .el-dialog__body {
        padding: 24px 32px 8px 32px;
    }
    .el-form {
        margin: 0 auto;
        max-width: 700px;
    }
    .el-form-item {
        margin-bottom: 18px;
    }
    .el-input, .el-select {
        min-width: 180px;
    }
    .el-button {
        border-radius: 4px;
        font-weight: 500;
    }
    .el-button + .el-button {
        margin-left: 8px;
    }
}

// 适配深色模式
@media (prefers-color-scheme: dark) {
  .material-ledger-container {
    background: #181a1b;
    .demo-form-inline, .operation-bar, .el-table {
      background: #23272e;
      color: #eee;
    }
    .el-table th, .el-table td {
      color: #eee;
    }
    .el-table--striped .el-table__body tr.el-table__row--striped td {
      background: #23272e;
    }
    .el-table__body tr:hover > td {
      background: #2a2d34 !important;
    }
    .el-dialog {
      background: #23272e;
      color: #eee;
    }
  }
}
</style>